create extension plpython3u;

create table test (id int , url varchar, val int[]);

insert into test values(1, '/home/lss/HSP-master/ml/n03196217_10139.JPEG');

CREATE OR REPLACE FUNCTION convert(url varchar)
  RETURNS int[] AS
$$
    import numpy as np
    import torch
    from torchvision import transforms
    from PIL import Image
    import sys

    def image_resize(resize_size=256, crop_size=224):
        
        return transforms.Compose([
            # transforms.ToPILImage(),
            transforms.Resize(resize_size),
            transforms.RandomResizedCrop(crop_size),
            # transforms.RandomHorizontalFlip(),
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
        ])
    model_dir = '/home/lss/HSP-master/ml/64bit_5e_0.8612_resnet50.pkl'
    sys.path.insert(0, '/home/lss/HSP-master/ml')
    model = torch.load(model_dir, map_location=torch.device('cpu'))
    model = model.module
    model.batch = 1
    image = Image.open(url)
    input = image_resize(resize_size=256, crop_size=224)(image).float()
    model.eval()
    input = torch.tensor(input.unsqueeze(0),requires_grad=False)
    y = model(input).detach().cpu().numpy()[0]
    T = 0
    y[y >= T] = 1
    y[y < T] = 0
    dim, = y.shape
    list = []
    for j in range(dim // 8):
        temp = 0
        for k in range(8):
            temp = temp * 2 + y[j * 8 + k]
        list.append(int(temp))
    return list
$$
LANGUAGE 'plpython3u';

update test set val = convert(url) where id = 1;